<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户登录注册组件</title>
  <script src="./js/vue.js"></script>
  <link rel="stylesheet" href="./css/denglu.css">
  <link rel="stylesheet" href="./css/zhuce.css">
</head>
<body>
  <div id="app" class="container">
    <div class="card">
      <div class="card-header">
        <h1>{{ isRegisterMode ? '用户注册' : '用户登录' }}</h1>
        <p>{{ isRegisterMode ? '创建您的新账户' : '欢迎回来，请登录您的账户' }}</p>
      </div>
      <div class="card-body">
        <!-- 模式切换 -->
        <div class="mode-switch">
          <button class="btn-mode" :class="!isRegisterMode ? 'active' : ''" @click="switchToLogin">登录</button>
          <button class="btn-mode" :class="isRegisterMode ? 'active' : ''" @click="switchToRegister">注册</button>
        </div>

        <!-- 登录状态指示器 -->
        <div class="status-indicator" :class="isLoggedIn ? 'status-online' : 'status-offline'">
          <div class="status-dot" :class="isLoggedIn ? 'dot-online' : 'dot-offline'"></div>
          {{ isLoggedIn ? '已登录' : isRegisterMode ? '注册模式' : '未登录' }}
        </div>
        
        <!-- 加载动画，使用v-show控制显示 -->
        <div class="loading-container" v-show="isLoading">
          <div class="loading-spinner"></div>
          <p class="loading-text">{{ loadingText }}</p>
        </div>
        
        <!-- 用户信息面板，使用v-show控制显示 -->
        <div class="user-info" v-show="isLoggedIn && !isRegisterMode && !isLoading">
          <div class="avatar">
            <span>{{ currentUser.name.charAt(0) }}</span>
          </div>
          <div class="user-name">{{ currentUser.name }}</div>
          <div class="user-email">{{ currentUser.email }}</div>
        </div>
        
        <!-- 登录表单，使用v-show控制显示 -->
        <div class="login-form" v-show="!isLoggedIn && !isRegisterMode && !isLoading">
          <div class="form-group">
            <label class="form-label">用户名</label>
            <input type="text" class="form-input" v-model="loginForm.username" placeholder="请输入用户名">
          </div>
          <div class="form-group">
            <label class="form-label">密码</label>
            <input type="password" class="form-input" v-model="loginForm.password" placeholder="请输入密码">
          </div>
          
          <!-- 登录按钮 -->
          <div style="margin-top: 30px;">
            <button class="btn btn-login" @click="login" :disabled="isLoading">登录</button>
          </div>
        </div>
        
        <!-- 注册表单，使用v-show控制显示 -->
        <div class="register-form" v-show="!isLoggedIn && isRegisterMode && !isLoading">
          <div class="form-group">
            <label class="form-label">用户名</label>
            <input type="text" class="form-input" v-model="registerForm.username" placeholder="请输入用户名" @blur="validateUsername">
            <!-- 用户名错误提示 -->
            <div class="error-message" v-show="showUsernameError">
              {{ usernameError }}
            </div>
          </div>
          
          <div class="form-group">
            <label class="form-label">邮箱</label>
            <input type="email" class="form-input" v-model="registerForm.email" placeholder="请输入邮箱" @blur="validateEmail">
            <!-- 邮箱错误提示 -->
            <div class="error-message" v-show="showEmailError">
              {{ emailError }}
            </div>
          </div>
          
          <div class="form-group">
            <label class="form-label">密码</label>
            <input type="password" class="form-input" v-model="registerForm.password" placeholder="请输入密码" @input="checkPasswordStrength">
            <!-- 密码强度提示 -->
            <div class="password-strength" v-show="registerForm.password">
              <div class="strength-text" :class="passwordStrengthClass">
                密码强度：{{ passwordStrengthText }}
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label class="form-label">确认密码</label>
            <input type="password" class="form-input" v-model="registerForm.confirmPassword" placeholder="请再次输入密码" @blur="validateConfirmPassword">
            <!-- 确认密码错误提示 -->
            <div class="error-message" v-show="showConfirmPasswordError">
              {{ confirmPasswordError }}
            </div>
          </div>
          
          <!-- 注册按钮 -->
          <div style="margin-top: 30px;">
            <button class="btn btn-register" @click="register" :disabled="!isFormValid || isLoading">注册</button>
          </div>
        </div>
        
        <!-- 登出按钮，使用v-show控制显示 -->
        <div style="margin-top: 30px;" v-show="isLoggedIn && !isRegisterMode && !isLoading">
          <button class="btn btn-logout" @click="confirmLogout" :disabled="isLoading">登出</button>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        isLoggedIn: false,
        isRegisterMode: false,
        isLoading: false,
        loadingText: '加载中...',
        currentUser: {
          name: '',
          email: ''
        },
        loginForm: {
          username: '',
          password: ''
        },
        registerForm: {
          username: '',
          email: '',
          password: '',
          confirmPassword: ''
        },
        // 表单验证相关数据
        showUsernameError: false,
        usernameError: '',
        showEmailError: false,
        emailError: '',
        showConfirmPasswordError: false,
        confirmPasswordError: '',
        passwordStrength: 0,
        passwordStrengthText: '',
        passwordStrengthClass: '',
        // 注册用户数据
        registeredUsers: {}
      },
      computed: {
        isFormValid() {
          return this.registerForm.username && 
                 this.registerForm.email && 
                 this.registerForm.password && 
                 this.registerForm.confirmPassword &&
                 !this.showUsernameError &&
                 !this.showEmailError &&
                 !this.showConfirmPasswordError &&
                 this.passwordStrength >= 1;
        }
      },
      created() {
        this.loadRegisteredUsers();
      },
      methods: {
        loadRegisteredUsers() {
          const users = localStorage.getItem('registeredUsers');
          if (users) {
            this.registeredUsers = JSON.parse(users);
          } else {
            this.registeredUsers = {};
          }
        },
        
        saveUserToStorage(userData) {
          const users = localStorage.getItem('registeredUsers');
          let userMap = {};
          
          if (users) {
            userMap = JSON.parse(users);
          }
          
          userMap[userData.username] = {
            username: userData.username,
            email: userData.email,
            password: userData.password
          };
          
          localStorage.setItem('registeredUsers', JSON.stringify(userMap));
          this.loadRegisteredUsers();
        },
        
        isUsernameExists(username) {
          return this.registeredUsers && this.registeredUsers[username];
        },
        
        async login() {
          if (!this.loginForm.username || !this.loginForm.password) {
            alert('请输入用户名和密码');
            return;
          }
          
          this.isLoading = true;
          this.loadingText = '登录中...';
          
          try {
            // 重新加载最新的用户数据
            this.loadRegisteredUsers();
            
            if (this.registeredUsers[this.loginForm.username]) {
              const userData = this.registeredUsers[this.loginForm.username];
              if (userData.password === this.loginForm.password) {
                this.isLoggedIn = true;
                this.currentUser = {
                  name: userData.username,
                  email: userData.email
                };
                alert('登录成功！');
              } else {
                alert('密码错误！');
                this.loginForm.password = '';
              }
            } else {
              alert('用户名不存在！');
              this.loginForm.password = '';
            }
          } catch (error) {
            alert('登录失败：' + error.message);
            this.loginForm.password = '';
          } finally {
            this.isLoading = false;
          }
        },
        
        confirmLogout() {
          if (confirm('确定要登出吗？')) {
            this.logout();
          }
        },
        
        async logout() {
          this.isLoading = true;
          this.loadingText = '登出中...';
          
          try {
            this.isLoggedIn = false;
            this.loginForm.username = '';
            this.loginForm.password = '';
            this.currentUser = {
              name: '',
              email: ''
            };
            alert('登出成功！');
          } catch (error) {
            alert('登出失败：' + error.message);
          } finally {
            this.isLoading = false;
          }
        },
        
        // 注册相关方法
        switchToLogin() {
          this.isRegisterMode = false;
          this.clearRegisterForm();
        },
        switchToRegister() {
          this.isRegisterMode = true;
          this.clearLoginForm();
        },
        clearLoginForm() {
          this.loginForm.username = '';
          this.loginForm.password = '';
        },
        clearRegisterForm() {
          this.registerForm.username = '';
          this.registerForm.email = '';
          this.registerForm.password = '';
          this.registerForm.confirmPassword = '';
          this.clearValidationErrors();
        },
        clearValidationErrors() {
          this.showUsernameError = false;
          this.showEmailError = false;
          this.showConfirmPasswordError = false;
          this.passwordStrength = 0;
          this.passwordStrengthText = '';
          this.passwordStrengthClass = '';
        },
        
        // 表单验证方法
        validateUsername() {
          if (!this.registerForm.username) {
            this.showUsernameError = true;
            this.usernameError = '用户名不能为空';
          } else if (this.registerForm.username.length < 2) {
            this.showUsernameError = true;
            this.usernameError = '用户名至少2个字符';
          } else if (this.isUsernameExists(this.registerForm.username)) {
            this.showUsernameError = true;
            this.usernameError = '用户名已存在';
          } else {
            this.showUsernameError = false;
          }
        },
        validateEmail() {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!this.registerForm.email) {
            this.showEmailError = true;
            this.emailError = '邮箱不能为空';
          } else if (!emailRegex.test(this.registerForm.email)) {
            this.showEmailError = true;
            this.emailError = '请输入有效的邮箱地址';
          } else {
            this.showEmailError = false;
          }
        },
        checkPasswordStrength() {
          let strength = 0;
          const password = this.registerForm.password;
          
          if (password.length >= 6) strength++;
          if (/[A-Z]/.test(password)) strength++;
          if (/[a-z]/.test(password)) strength++;
          if (/[0-9]/.test(password)) strength++;
          if (/[^A-Za-z0-9]/.test(password)) strength++;
          
          this.passwordStrength = strength;
          
          // 设置密码强度显示
          if (strength <= 1) {
            this.passwordStrengthText = '弱';
            this.passwordStrengthClass = 'weak';
          } else if (strength <= 3) {
            this.passwordStrengthText = '中';
            this.passwordStrengthClass = 'medium';
          } else {
            this.passwordStrengthText = '强';
            this.passwordStrengthClass = 'strong';
          }
        },
        validateConfirmPassword() {
          if (!this.registerForm.confirmPassword) {
            this.showConfirmPasswordError = true;
            this.confirmPasswordError = '请确认密码';
          } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
            this.showConfirmPasswordError = true;
            this.confirmPasswordError = '两次输入的密码不一致';
          } else {
            this.showConfirmPasswordError = false;
          }
        },
        
        async register() {
          // 验证所有字段
          this.validateUsername();
          this.validateEmail();
          this.validateConfirmPassword();
          
          if (!this.isFormValid) {
            alert('请完善注册信息');
            return;
          }
          
          this.isLoading = true;
          this.loadingText = '注册中...';
          
          try {
            // 保存用户信息到localStorage
            this.saveUserToStorage({
              username: this.registerForm.username,
              email: this.registerForm.email,
              password: this.registerForm.password
            });
            
            alert('注册成功！用户名：' + this.registerForm.username);
            
            // 注册成功后切换到登录页面
            this.switchToLogin();
            this.loginForm.username = this.registerForm.username;
          } catch (error) {
            alert('注册失败：' + error.message);
          } finally {
            this.isLoading = false;
          }
        }
      }
    });
  </script>